<template>
  <div class="login-container" :data-theme="currentTheme.id">
    <!-- 主题切换器 -->
    <div class="theme-switcher">
      <el-dropdown @command="handleThemeChange" trigger="click">
        <el-button 
          circle 
          class="theme-btn"
          aria-label="切换主题"
          title="切换主题"
        >
          <span class="theme-icon">🎨</span>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item 
              command="default"
              :class="{ 'is-active': currentThemeId === 'default' }"
            >
              <el-icon class="dropdown-icon"><DataAnalysis /></el-icon>
              <span>数据中台</span>
            </el-dropdown-item>
            <el-dropdown-item 
              command="travel"
              :class="{ 'is-active': currentThemeId === 'travel' }"
            >
              <el-icon class="dropdown-icon"><Van /></el-icon>
              <span>出行行业</span>
            </el-dropdown-item>
            <el-dropdown-item 
              command="housing"
              :class="{ 'is-active': currentThemeId === 'housing' }"
            >
              <el-icon class="dropdown-icon"><House /></el-icon>
              <span>租房行业</span>
            </el-dropdown-item>
            <el-dropdown-item 
              command="ai"
              :class="{ 'is-active': currentThemeId === 'ai' }"
            >
              <el-icon class="dropdown-icon"><MagicStick /></el-icon>
              <span>AI行业</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 动态背景 -->
    <div class="animated-background">
      <!-- 连线式粒子效果 - Canvas 实现 -->
      <canvas ref="particleCanvas" class="particle-canvas"></canvas>
      
      <!-- 简化后的渐变光球 - 只保留一个主光球 -->
      <div 
        class="gradient-orb main-orb"
        :style="{ background: `radial-gradient(circle at 30% 40%, ${currentTheme.colors.orbColors[0]} 0%, transparent 60%)` }"
      ></div>
      
      <!-- 波浪效果 - 简化为单层 -->
      <div class="wave-container">
        <svg class="wave" viewBox="0 0 1200 150" preserveAspectRatio="none">
          <defs>
            <linearGradient id="waveGradient" x1="0%" y1="0%" x2="0%" y2="100%">
              <stop offset="0%" :style="`stop-color:${currentTheme.colors.primary};stop-opacity:0.3`" />
              <stop offset="100%" :style="`stop-color:${currentTheme.colors.secondary};stop-opacity:0.15`" />
            </linearGradient>
          </defs>
          <path d="M0,60 C300,90 600,40 900,70 C1050,85 1150,60 1200,75 L1200,150 L0,150 Z" fill="url(#waveGradient)">
            <animate attributeName="d" dur="12s" repeatCount="indefinite"
              values="M0,60 C300,90 600,40 900,70 C1050,85 1150,60 1200,75 L1200,150 L0,150 Z;
                      M0,75 C300,45 600,95 900,55 C1050,65 1150,90 1200,60 L1200,150 L0,150 Z;
                      M0,60 C300,90 600,40 900,70 C1050,85 1150,60 1200,75 L1200,150 L0,150 Z" />
          </path>
        </svg>
      </div>
    </div>

    <!-- 主内容 -->
    <div class="main-content">
      <!-- 左侧品牌区 - 精简版 -->
      <div class="brand-section">
        <div class="brand-wrapper">
          <!-- Logo 和标题 -->
          <div class="logo-area">
            <div class="logo-icon">
              <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
                <defs>
                  <linearGradient id="logoGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                    <stop offset="0%" :style="`stop-color:${currentTheme.colors.primary};stop-opacity:1`" />
                    <stop offset="100%" :style="`stop-color:${currentTheme.colors.secondary};stop-opacity:1`" />
                  </linearGradient>
                </defs>
                <circle cx="50" cy="50" r="45" fill="url(#logoGradient)" />
                <text 
                  x="50" 
                  y="70" 
                  font-size="55" 
                  font-weight="bold" 
                  fill="white" 
                  text-anchor="middle" 
                  font-family="Arial, sans-serif"
                >
                  {{ currentTheme.logo.text }}
                </text>
              </svg>
            </div>
            <h1 class="brand-title">{{ currentTheme.branding.title }}</h1>
            <p class="brand-tagline">{{ currentTheme.branding.subtitle }}</p>
            <p class="brand-slogan">{{ currentTheme.branding.slogan }}</p>
          </div>
        </div>
      </div>

      <!-- 右侧表单区 -->
      <div class="form-section">
        <div class="form-wrapper">
          <!-- 玻璃态卡片 -->
          <div class="glass-card">
            <!-- 标签切换 -->
            <div class="tab-switcher" v-if="currentView === 'main'">
              <div class="tab-buttons">
                <button
                  :class="['tab-btn', { active: loginType === 'login' }]"
                  @click="switchTab('login')"
                >
                  <el-icon class="tab-icon"><Lock /></el-icon>
                  <span class="tab-label">登录</span>
                </button>
                <button
                  :class="['tab-btn', { active: loginType === 'register' }]"
                  @click="switchTab('register')"
                >
                  <el-icon class="tab-icon"><UserFilled /></el-icon>
                  <span class="tab-label">注册</span>
                </button>
              </div>
            </div>

            <!-- 返回按钮（忘记密码页面） -->
            <div class="back-header" v-if="currentView === 'forgot'">
              <el-button text @click="currentView = 'main'">
                <el-icon><ArrowLeft /></el-icon>
                <span>返回</span>
              </el-button>
            </div>

            <!-- 表单内容 -->
            <div class="form-content">
              <!-- 登录表单 -->
              <login-form 
                v-if="currentView === 'main' && loginType === 'login'" 
                key="login"
                @forgot-password="currentView = 'forgot'"
              />
              <!-- 注册表单 -->
              <register 
                v-else-if="currentView === 'main' && loginType === 'register'" 
                key="register" 
                @register-success="handleRegisterSuccess" 
              />
              <!-- 忘记密码 -->
              <forgot-password
                v-else-if="currentView === 'forgot'"
                key="forgot"
                @back="currentView = 'main'"
                @success="handleForgotSuccess"
              />
            </div>
          </div>

          <!-- 底部信息 - 已隐藏 -->
          <!-- <div class="bottom-info">
            <div class="help-links">
              <router-link to="/help-center" class="link-item">
                <span class="link-icon">❓</span>
                <span>帮助中心</span>
              </router-link>
              <span class="separator">·</span>
              <router-link to="/privacy-policy" class="link-item">
                <span class="link-icon">🔒</span>
                <span>隐私政策</span>
              </router-link>
              <span class="separator">·</span>
              <router-link to="/terms-of-service" class="link-item">
                <span class="link-icon">📄</span>
                <span>服务条款</span>
              </router-link>
            </div>
          </div> -->
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <footer class="page-footer">
      <p>© 2024 {{ companyName }}. All rights reserved.</p>
    </footer>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { 
  ArrowLeft,
  DataAnalysis,
  Van,
  House,
  MagicStick,
  Lock,
  UserFilled
} from '@element-plus/icons-vue';
import LoginForm from '../components/LoginForm.vue';
import Register from '../components/Register.vue';
import ForgotPassword from '../components/ForgotPassword.vue';
import { getTheme, applyTheme, type ThemeConfig } from '../config/themes';

defineOptions({
  name: 'Login',
});

const companyName = ref(import.meta.env.VITE_APP_COMPANY_NAME || 'MicroService');
const loginType = ref<'login' | 'register'>('login');
const currentView = ref<'main' | 'forgot'>('main');
const currentThemeId = ref('default');
const currentTheme = ref<ThemeConfig>(getTheme('default'));
const particleCanvas = ref<HTMLCanvasElement | null>(null);

const switchTab = (type: 'login' | 'register') => {
  loginType.value = type;
};

const handleRegisterSuccess = () => {
  loginType.value = 'login';
  currentView.value = 'main';
};

const handleForgotSuccess = () => {
  loginType.value = 'login';
  currentView.value = 'main';
};

const handleThemeChange = (themeId: string) => {
  currentThemeId.value = themeId;
  currentTheme.value = getTheme(themeId);
  applyTheme(currentTheme.value);
  
  // 保存到 localStorage
  localStorage.setItem('login-theme', themeId);
  
  // 重新初始化粒子效果（根据新主题）
  if (particleCanvas.value) {
    initParticles(particleCanvas.value);
  }
};

// ==================== 多主题粒子系统 ====================
type ParticleEffectType = 'ai' | 'starry' | 'meteor' | 'bubble';

interface Particle {
  x: number;
  y: number;
  vx: number;
  vy: number;
  radius: number;
  opacity: number;
  color: string;
  hue: number;
  pulsePhase: number;
  pulseSpeed: number;
  // 流星特有
  length?: number;
  speed?: number;
  // 气泡特有
  floatSpeed?: number;
}

interface EnergyFlow {
  fromIndex: number;
  toIndex: number;
  progress: number;
  speed: number;
}

let particles: Particle[] = [];
let energyFlows: EnergyFlow[] = [];
let animationFrameId: number | null = null;
let frameCount = 0;
let currentEffect: ParticleEffectType = 'starry';

// 根据主题ID获取粒子效果类型
const getEffectByTheme = (themeId: string): ParticleEffectType => {
  const effectMap: Record<string, ParticleEffectType> = {
    'ai': 'ai',           // AI主题 → 神经网络
    'default': 'starry',  // 数据中台 → 星空闪烁
    'travel': 'meteor',   // 出行 → 流星
    'housing': 'bubble',  // 租房 → 气泡
  };
  return effectMap[themeId] || 'starry';
};

// 获取主题对应的颜色
const getColorsByTheme = (themeId: string) => {
  const theme = currentTheme.value;
  const primary = theme.colors.primary;
  const secondary = theme.colors.secondary;
  
  // 解析颜色为RGB
  const parseColor = (hex: string) => {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    return { r, g, b };
  };
  
  const primaryRGB = parseColor(primary);
  const secondaryRGB = parseColor(secondary);
  
  // 根据主题生成配色
  if (themeId === 'ai') {
    return [
      { r: 0, g: 191, b: 255 },
      { r: 138, g: 43, b: 226 },
      { r: 0, g: 255, b: 255 },
      { r: 138, g: 0, b: 255 },
      { r: 64, g: 224, b: 208 },
    ];
  } else if (themeId === 'travel') {
    return [
      { r: 255, g: 107, b: 53 },   // 橙色
      { r: 255, g: 184, b: 0 },    // 金黄
      { r: 255, g: 140, b: 66 },   // 浅橙
      primaryRGB,
      secondaryRGB,
    ];
  } else if (themeId === 'housing') {
    return [
      { r: 0, g: 174, b: 102 },    // 绿色
      { r: 74, g: 144, b: 226 },   // 蓝色
      { r: 0, g: 200, b: 120 },    // 浅绿
      primaryRGB,
      secondaryRGB,
    ];
  } else {
    return [
      primaryRGB,
      secondaryRGB,
      { r: 150, g: 90, b: 200 },   // 紫色
      { r: 102, g: 126, b: 234 },  // 蓝色
      { r: 118, g: 75, b: 162 },   // 深紫
    ];
  }
};

// 初始化粒子（根据主题）
const initParticles = (canvas: HTMLCanvasElement) => {
  particles = [];
  energyFlows = [];
  frameCount = 0;
  
  const themeId = currentThemeId.value;
  currentEffect = getEffectByTheme(themeId);
  const colors = getColorsByTheme(themeId);
  
  // 根据效果类型初始化不同的粒子（优化：更简洁低调）
  switch (currentEffect) {
    case 'ai':
      // AI神经网络：30个节点（减少数量）
      for (let i = 0; i < 30; i++) {
        const color = colors[Math.floor(Math.random() * colors.length)];
        particles.push({
          x: Math.random() * canvas.width,
          y: Math.random() * canvas.height,
          vx: (Math.random() - 0.5) * 0.2,
          vy: (Math.random() - 0.5) * 0.2,
          radius: Math.random() * 1.5 + 1.5,
          opacity: Math.random() * 0.2 + 0.3, // 降低透明度
          color: `rgba(${color.r}, ${color.g}, ${color.b}, 1)`,
          hue: Math.random() * 360,
          pulsePhase: Math.random() * Math.PI * 2,
          pulseSpeed: Math.random() * 0.01 + 0.005,
        });
      }
      // 初始化能量流（减少）
      for (let i = 0; i < 2; i++) {
        createEnergyFlow();
      }
      break;
      
    case 'starry':
      // 星空闪烁：50个星星（减少数量）
      for (let i = 0; i < 50; i++) {
        const color = colors[Math.floor(Math.random() * colors.length)];
        particles.push({
          x: Math.random() * canvas.width,
          y: Math.random() * canvas.height,
          vx: 0,
          vy: 0,
          radius: Math.random() * 1.5 + 0.8,
          opacity: Math.random() * 0.25 + 0.2, // 更低透明度
          color: `rgba(${color.r}, ${color.g}, ${color.b}, 1)`,
          hue: Math.random() * 360,
          pulsePhase: Math.random() * Math.PI * 2,
          pulseSpeed: Math.random() * 0.01 + 0.008,
        });
      }
      break;
      
    case 'meteor':
      // 流星：6颗流星（大幅减少）
      for (let i = 0; i < 6; i++) {
        const color = colors[Math.floor(Math.random() * colors.length)];
        particles.push({
          x: Math.random() * canvas.width,
          y: -50 - Math.random() * 500, // 分散出现
          vx: (Math.random() - 0.5) * 1.5,
          vy: Math.random() * 2 + 1.5,
          radius: Math.random() * 1 + 0.8,
          opacity: Math.random() * 0.3 + 0.3, // 降低透明度
          color: `rgba(${color.r}, ${color.g}, ${color.b}, 1)`,
          hue: Math.random() * 360,
          pulsePhase: 0,
          pulseSpeed: 0,
          length: Math.random() * 40 + 30,
          speed: Math.random() * 2 + 1.5,
        });
      }
      break;
      
    case 'bubble':
      // 气泡漂浮：20个气泡（减半）
      for (let i = 0; i < 20; i++) {
        const color = colors[Math.floor(Math.random() * colors.length)];
        particles.push({
          x: Math.random() * canvas.width,
          y: Math.random() * canvas.height,
          vx: (Math.random() - 0.5) * 0.2,
          vy: -(Math.random() * 0.3 + 0.15),
          radius: Math.random() * 12 + 8,
          opacity: Math.random() * 0.12 + 0.08, // 更低透明度
          color: `rgba(${color.r}, ${color.g}, ${color.b}, 1)`,
          hue: Math.random() * 360,
          pulsePhase: Math.random() * Math.PI * 2,
          pulseSpeed: Math.random() * 0.008 + 0.004,
          floatSpeed: Math.random() * 0.3 + 0.15,
        });
      }
      break;
  }
};

// 创建能量流
const createEnergyFlow = () => {
  if (particles.length < 2) return;
  
  const fromIndex = Math.floor(Math.random() * particles.length);
  let toIndex = Math.floor(Math.random() * particles.length);
  
  // 确保不是同一个粒子
  while (toIndex === fromIndex) {
    toIndex = Math.floor(Math.random() * particles.length);
  }
  
  energyFlows.push({
    fromIndex,
    toIndex,
    progress: 0,
    speed: Math.random() * 0.005 + 0.005, // 0.005-0.01
  });
};

// 绘制粒子（根据效果类型）
const drawParticles = (canvas: HTMLCanvasElement) => {
  const ctx = canvas.getContext('2d');
  if (!ctx) return;
  
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  switch (currentEffect) {
    case 'ai':
      drawAIEffect(ctx, canvas);
      break;
    case 'starry':
      drawStarryEffect(ctx);
      break;
    case 'meteor':
      drawMeteorEffect(ctx, canvas);
      break;
    case 'bubble':
      drawBubbleEffect(ctx, canvas);
      break;
  }
};

// AI 神经网络效果
const drawAIEffect = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) => {
  
  // 连线距离阈值（缩短距离，减少连线）
  const connectDistance = 150;
  const connections: Array<{particleA: Particle, particleB: Particle, distance: number}> = [];
  
  // 收集所有连接
  particles.forEach((particleA, indexA) => {
    particles.slice(indexA + 1).forEach((particleB) => {
      const dx = particleA.x - particleB.x;
      const dy = particleA.y - particleB.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      if (distance < connectDistance) {
        connections.push({ particleA, particleB, distance });
      }
    });
  });
  
  // 绘制神经网络连线（更淡）
  connections.forEach(({ particleA, particleB, distance }) => {
    const opacity = (1 - distance / connectDistance) * 0.25; // 降低透明度
    
    // 创建渐变连线
    const gradient = ctx.createLinearGradient(
      particleA.x, particleA.y,
      particleB.x, particleB.y
    );
    
    const colorA = particleA.color.match(/\d+/g)?.map(Number) || [0, 191, 255];
    const colorB = particleB.color.match(/\d+/g)?.map(Number) || [138, 43, 226];
    
    gradient.addColorStop(0, `rgba(${colorA[0]}, ${colorA[1]}, ${colorA[2]}, ${opacity})`);
    gradient.addColorStop(0.5, `rgba(${(colorA[0] + colorB[0]) / 2}, ${(colorA[1] + colorB[1]) / 2}, ${(colorA[2] + colorB[2]) / 2}, ${opacity * 1.2})`);
    gradient.addColorStop(1, `rgba(${colorB[0]}, ${colorB[1]}, ${colorB[2]}, ${opacity})`);
    
    ctx.strokeStyle = gradient;
    ctx.lineWidth = 1; // 更细的线条
    ctx.beginPath();
    ctx.moveTo(particleA.x, particleA.y);
    ctx.lineTo(particleB.x, particleB.y);
    ctx.stroke();
  });
  
  // 绘制能量流（数据流动效果）
  energyFlows.forEach(flow => {
    const from = particles[flow.fromIndex];
    const to = particles[flow.toIndex];
    
    if (!from || !to) return;
    
    const x = from.x + (to.x - from.x) * flow.progress;
    const y = from.y + (to.y - from.y) * flow.progress;
    
    // 能量点（更小更淡）
    const gradient = ctx.createRadialGradient(x, y, 0, x, y, 4);
    gradient.addColorStop(0, 'rgba(255, 255, 255, 0.6)');
    gradient.addColorStop(0.3, 'rgba(0, 255, 255, 0.5)');
    gradient.addColorStop(1, 'rgba(0, 255, 255, 0)');
    
    ctx.fillStyle = gradient;
    ctx.beginPath();
    ctx.arc(x, y, 4, 0, Math.PI * 2);
    ctx.fill();
    
    // 能量尾迹（更淡）
    const tailLength = 20;
    const tailX = from.x + (to.x - from.x) * Math.max(0, flow.progress - 0.1);
    const tailY = from.y + (to.y - from.y) * Math.max(0, flow.progress - 0.1);
    
    const tailGradient = ctx.createLinearGradient(tailX, tailY, x, y);
    tailGradient.addColorStop(0, 'rgba(0, 255, 255, 0)');
    tailGradient.addColorStop(1, 'rgba(0, 255, 255, 0.35)');
    
    ctx.strokeStyle = tailGradient;
    ctx.lineWidth = 1.5;
    ctx.beginPath();
    ctx.moveTo(tailX, tailY);
    ctx.lineTo(x, y);
    ctx.stroke();
  });
  
  // 绘制粒子（带脉冲效果）
  particles.forEach((particle) => {
    const colorMatch = particle.color.match(/\d+/g);
    if (!colorMatch) return;
    
    const [r, g, b] = colorMatch.map(Number);
    
    // 计算脉冲
    const pulse = Math.sin(particle.pulsePhase) * 0.3 + 0.7; // 0.4-1.0
    const currentRadius = particle.radius * pulse;
    
    // 外层光晕（更柔和）
    const glowRadius = currentRadius * 3;
    const glowGradient = ctx.createRadialGradient(
      particle.x, particle.y, 0,
      particle.x, particle.y, glowRadius
    );
    glowGradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, ${particle.opacity * 0.5 * pulse})`);
    glowGradient.addColorStop(0.4, `rgba(${r}, ${g}, ${b}, ${particle.opacity * 0.25 * pulse})`);
    glowGradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
    
    ctx.fillStyle = glowGradient;
    ctx.beginPath();
    ctx.arc(particle.x, particle.y, glowRadius, 0, Math.PI * 2);
    ctx.fill();
    
    // 粒子核心（更简单）
    const coreGradient = ctx.createRadialGradient(
      particle.x, particle.y, 0,
      particle.x, particle.y, currentRadius
    );
    coreGradient.addColorStop(0, `rgba(255, 255, 255, ${particle.opacity * 0.8})`);
    coreGradient.addColorStop(0.5, `rgba(${r}, ${g}, ${b}, ${particle.opacity * 0.7})`);
    coreGradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, ${particle.opacity * 0.4})`);
    
    ctx.fillStyle = coreGradient;
    ctx.shadowBlur = 6 * pulse; // 减弱阴影
    ctx.shadowColor = `rgba(${r}, ${g}, ${b}, 0.6)`;
    ctx.beginPath();
    ctx.arc(particle.x, particle.y, currentRadius, 0, Math.PI * 2);
    ctx.fill();
    ctx.shadowBlur = 0;
    
    // 移除脉冲环（减少视觉干扰）
  });
};

// 星空闪烁效果
const drawStarryEffect = (ctx: CanvasRenderingContext2D) => {
  particles.forEach((particle) => {
    const colorMatch = particle.color.match(/\d+/g);
    if (!colorMatch) return;
    const [r, g, b] = colorMatch.map(Number);
    
    // 闪烁透明度
    const twinkle = Math.sin(particle.pulsePhase) * 0.5 + 0.5;
    const currentOpacity = particle.opacity * twinkle;
    
    // 绘制星星光晕
    const glowGradient = ctx.createRadialGradient(
      particle.x, particle.y, 0,
      particle.x, particle.y, particle.radius * 3
    );
    glowGradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, ${currentOpacity})`);
    glowGradient.addColorStop(0.5, `rgba(${r}, ${g}, ${b}, ${currentOpacity * 0.5})`);
    glowGradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
    
    ctx.fillStyle = glowGradient;
    ctx.beginPath();
    ctx.arc(particle.x, particle.y, particle.radius * 3, 0, Math.PI * 2);
    ctx.fill();
    
    // 星星核心
    ctx.fillStyle = `rgba(255, 255, 255, ${currentOpacity})`;
    ctx.shadowBlur = 4 * twinkle;
    ctx.shadowColor = `rgba(${r}, ${g}, ${b}, ${currentOpacity})`;
    ctx.beginPath();
    ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
    ctx.fill();
    ctx.shadowBlur = 0;
  });
};

// 流星效果
const drawMeteorEffect = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) => {
  particles.forEach((particle) => {
    const colorMatch = particle.color.match(/\d+/g);
    if (!colorMatch) return;
    const [r, g, b] = colorMatch.map(Number);
    
    // 绘制流星尾迹
    const tailLength = particle.length || 50;
    const gradient = ctx.createLinearGradient(
      particle.x, particle.y,
      particle.x - particle.vx * 10, particle.y - particle.vy * 10
    );
    gradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, ${particle.opacity})`);
    gradient.addColorStop(0.5, `rgba(${r}, ${g}, ${b}, ${particle.opacity * 0.5})`);
    gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
    
    ctx.strokeStyle = gradient;
    ctx.lineWidth = particle.radius * 2;
    ctx.lineCap = 'round';
    ctx.beginPath();
    ctx.moveTo(particle.x, particle.y);
    ctx.lineTo(particle.x - particle.vx * 10, particle.y - particle.vy * 10);
    ctx.stroke();
    
    // 绘制流星头部
    const headGradient = ctx.createRadialGradient(
      particle.x, particle.y, 0,
      particle.x, particle.y, particle.radius * 3
    );
    headGradient.addColorStop(0, 'rgba(255, 255, 255, 1)');
    headGradient.addColorStop(0.4, `rgba(${r}, ${g}, ${b}, ${particle.opacity})`);
    headGradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
    
    ctx.fillStyle = headGradient;
    ctx.shadowBlur = 10;
    ctx.shadowColor = `rgba(${r}, ${g}, ${b}, 1)`;
    ctx.beginPath();
    ctx.arc(particle.x, particle.y, particle.radius * 3, 0, Math.PI * 2);
    ctx.fill();
    ctx.shadowBlur = 0;
  });
};

// 气泡漂浮效果
const drawBubbleEffect = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) => {
  particles.forEach((particle) => {
    const colorMatch = particle.color.match(/\d+/g);
    if (!colorMatch) return;
    const [r, g, b] = colorMatch.map(Number);
    
    // 轻微呼吸效果
    const breathe = Math.sin(particle.pulsePhase) * 0.1 + 0.95;
    const currentRadius = particle.radius * breathe;
    
    // 气泡外圈（高光）
    const outerGradient = ctx.createRadialGradient(
      particle.x - currentRadius * 0.3,
      particle.y - currentRadius * 0.3,
      0,
      particle.x,
      particle.y,
      currentRadius
    );
    outerGradient.addColorStop(0, `rgba(255, 255, 255, ${particle.opacity * 0.6})`);
    outerGradient.addColorStop(0.3, `rgba(${r}, ${g}, ${b}, ${particle.opacity * 0.3})`);
    outerGradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, ${particle.opacity * 0.1})`);
    
    ctx.fillStyle = outerGradient;
    ctx.beginPath();
    ctx.arc(particle.x, particle.y, currentRadius, 0, Math.PI * 2);
    ctx.fill();
    
    // 气泡边框
    ctx.strokeStyle = `rgba(${r}, ${g}, ${b}, ${particle.opacity * 0.4})`;
    ctx.lineWidth = 1.5;
    ctx.beginPath();
    ctx.arc(particle.x, particle.y, currentRadius, 0, Math.PI * 2);
    ctx.stroke();
    
    // 高光点
    ctx.fillStyle = `rgba(255, 255, 255, ${particle.opacity * 0.8})`;
    ctx.beginPath();
    ctx.arc(
      particle.x - currentRadius * 0.4,
      particle.y - currentRadius * 0.4,
      currentRadius * 0.2,
      0,
      Math.PI * 2
    );
    ctx.fill();
  });
};

// 更新粒子位置（根据效果类型）
const updateParticles = (canvas: HTMLCanvasElement) => {
  frameCount++;
  
  switch (currentEffect) {
    case 'ai':
      // AI 效果：粒子移动 + 能量流
      particles.forEach((particle) => {
        particle.x += particle.vx;
        particle.y += particle.vy;
        particle.pulsePhase += particle.pulseSpeed;
        
        // 边界反弹
        if (particle.x < 0 || particle.x > canvas.width) {
          particle.vx = -particle.vx;
          particle.x = Math.max(0, Math.min(canvas.width, particle.x));
        }
        if (particle.y < 0 || particle.y > canvas.height) {
          particle.vy = -particle.vy;
          particle.y = Math.max(0, Math.min(canvas.height, particle.y));
        }
      });
      
      // 更新能量流
      energyFlows = energyFlows.filter(flow => {
        flow.progress += flow.speed;
        return flow.progress < 1.1;
      });
      
      if (frameCount % 90 === 0 && energyFlows.length < 4) {
        createEnergyFlow();
      }
      break;
      
    case 'starry':
      // 星空效果：只闪烁，不移动
      particles.forEach((particle) => {
        particle.pulsePhase += particle.pulseSpeed;
      });
      break;
      
    case 'meteor':
      // 流星效果：快速下落
      particles.forEach((particle) => {
        particle.x += particle.vx;
        particle.y += particle.vy;
        
        // 超出屏幕后重置
        if (particle.y > canvas.height + 50) {
          particle.x = Math.random() * canvas.width;
          particle.y = -50;
          particle.vx = (Math.random() - 0.5) * 2;
          particle.vy = Math.random() * 3 + 2;
        }
      });
      break;
      
    case 'bubble':
      // 气泡效果：向上漂浮
      particles.forEach((particle) => {
        particle.x += particle.vx;
        particle.y += particle.vy;
        particle.pulsePhase += particle.pulseSpeed;
        
        // 轻微左右摆动
        particle.x += Math.sin(particle.pulsePhase) * 0.5;
        
        // 超出顶部后重置到底部
        if (particle.y < -particle.radius * 2) {
          particle.y = canvas.height + particle.radius * 2;
          particle.x = Math.random() * canvas.width;
        }
        
        // 边界检测
        if (particle.x < 0) particle.x = canvas.width;
        if (particle.x > canvas.width) particle.x = 0;
      });
      break;
  }
};

// 动画循环
const animate = (canvas: HTMLCanvasElement) => {
  updateParticles(canvas);
  drawParticles(canvas);
  animationFrameId = requestAnimationFrame(() => animate(canvas));
};

// 调整 Canvas 尺寸
const resizeCanvas = (canvas: HTMLCanvasElement) => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  initParticles(canvas);
};

// 初始化主题和粒子系统
onMounted(() => {
  const savedTheme = localStorage.getItem('login-theme') || 'default';
  handleThemeChange(savedTheme);
  
  // 初始化粒子系统
  if (particleCanvas.value) {
    const canvas = particleCanvas.value;
    resizeCanvas(canvas);
    animate(canvas);
    
    // 监听窗口大小变化
    window.addEventListener('resize', () => resizeCanvas(canvas));
  }
});

// 清理
onUnmounted(() => {
  if (animationFrameId !== null) {
    cancelAnimationFrame(animationFrameId);
  }
  window.removeEventListener('resize', () => {});
});
</script>

<style lang="less" scoped>
// ==================== CSS变量 - 统一字号体系 ====================
:root {
  --font-size-xs: 12px;    // 辅助文字
  --font-size-sm: 14px;    // 正文
  --font-size-md: 16px;    // 强调文字
  --font-size-lg: 20px;    // 副标题
  --font-size-xl: 32px;    // 主标题
  --border-radius: 8px;    // 统一圆角
}

// ==================== 主容器 ====================
.login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow-x: hidden;
  overflow-y: auto;
  background: linear-gradient(135deg, var(--theme-gradient-start, #667eea) 0%, var(--theme-gradient-end, #764ba2) 100%);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  transition: background 0.5s ease;
  
  // 禁止选择装饰性文字
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

// ==================== 主题切换器 ====================
.theme-switcher {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 100;

  .theme-btn {
    width: 48px;
    height: 48px;
    background: transparent;
    backdrop-filter: none;
    border: none;
    border-radius: 50%;
    box-shadow: none;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &:hover {
      transform: scale(1.1);
      background: rgba(255, 255, 255, 0.1);
    }

    &:active {
      transform: scale(1);
    }

    .theme-icon {
      font-size: 24px;
      filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
    }
  }

  :deep(.el-dropdown-menu__item) {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: var(--font-size-sm);
    padding: 8px 16px;
    transition: all 0.3s;

    &.is-active {
      color: var(--theme-primary);
      background: rgba(102, 126, 234, 0.08);
      font-weight: 500;
    }

    .dropdown-icon {
      font-size: 16px;
    }

    &:hover {
      background: rgba(0, 0, 0, 0.04);
    }
  }
}

// ==================== 动态背景 ====================
.animated-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
  overflow: hidden;

  // Canvas 粒子系统 - 连线式（参考 GitHub Universe/区块链）
  .particle-canvas {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;
  }

  // 简化的渐变光球
  .gradient-orb {
    position: absolute;
    border-radius: 50%;
    filter: blur(100px);
    opacity: 0.4;
    animation: float 10s ease-in-out infinite;
    pointer-events: none;

    &.main-orb {
      width: 600px;
      height: 600px;
      top: -100px;
      right: -100px;
    }
  }

  // 简化的波浪容器
  .wave-container {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 120px;
    overflow: hidden;
    pointer-events: none;
    z-index: 10;

    .wave {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0.8;
    }
  }
}

@keyframes float {
  0%, 100% {
    transform: translate(0, 0) scale(1);
  }
  33% {
    transform: translate(30px, -30px) scale(1.1);
  }
  66% {
    transform: translate(-20px, 20px) scale(0.9);
  }
}

// Canvas 连线式粒子不需要 CSS 动画

// ==================== 主内容区 ====================
.main-content {
  flex: 1 0 auto; /* 允许收缩但不自动伸展 */
  display: flex;
  align-items: center;
  justify-content: center; /* 居中对齐，而非两端对齐 */
  padding: 20px 50px 10px;
  gap: 64px; /* 控制在黄金比例范围内，更紧凑 */
  z-index: 1;
  position: relative;
  max-width: 1200px; /* 控制总宽度，保持聚焦 */
  margin: 0 auto;
  width: 100%;

  @media (max-width: 1200px) {
    padding: 20px 40px 10px;
    gap: 48px;
  }

  @media (max-width: 768px) {
    flex-direction: column;
    padding: 20px 20px 10px;
    gap: 30px;
  }
}

// ==================== 左侧品牌区 - 精简版 ====================
.brand-section {
  flex: 0 0 auto;
  width: 400px;
  animation: slideInLeft 0.8s cubic-bezier(0.16, 1, 0.3, 1);

  @media (max-width: 1200px) {
    width: 360px;
  }

  @media (max-width: 768px) {
    width: 100%;
    text-align: center;
    animation: none;
    margin-bottom: 20px;
  }

  .brand-wrapper {
    .logo-area {
      text-align: center;

      .logo-icon {
        width: 80px;
        height: 80px;
        margin: 0 auto 20px;
        filter: drop-shadow(0 8px 24px rgba(0, 0, 0, 0.3));
        animation: logoFloat 3s ease-in-out infinite;

        svg {
          width: 100%;
          height: 100%;
        }
      }

      .brand-title {
        font-size: var(--font-size-xl);
        font-weight: 700;
        color: white;
        margin: 0 0 12px;
        letter-spacing: -0.5px;
        text-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);

        @media (max-width: 768px) {
          font-size: 28px;
        }
      }

      .brand-tagline {
        font-size: var(--font-size-md);
        color: rgba(255, 255, 255, 0.9);
        margin: 0 0 8px;
        font-weight: 400;
        line-height: 1.6;

        @media (max-width: 768px) {
          font-size: var(--font-size-sm);
        }
      }

      .brand-slogan {
        font-size: var(--font-size-sm);
        color: rgba(255, 255, 255, 0.75);
        margin: 0;
        font-weight: 300;
        letter-spacing: 2px;

        @media (max-width: 768px) {
          font-size: var(--font-size-xs);
        }
      }
    }
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-60px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes logoFloat {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

// ==================== 右侧表单区 ====================
.form-section {
  flex: 0 0 auto;
  width: 440px;
  animation: slideInRight 0.8s cubic-bezier(0.16, 1, 0.3, 1);

  @media (max-width: 1200px) {
    width: 420px;
  }

  @media (max-width: 768px) {
    width: 100%;
    animation: none;
  }

  .form-wrapper {
    .glass-card {
      background: rgba(255, 255, 255, 0.98);
      backdrop-filter: blur(24px);
      border-radius: 12px;
      padding: 36px;
      box-shadow: 
        0 10px 40px rgba(0, 0, 0, 0.1),
        0 0 0 1px rgba(255, 255, 255, 0.8) inset;
      border: 1px solid rgba(255, 255, 255, 0.5);
      position: relative;
      
      // 添加背景遮罩，提升对比度
      &::before {
        content: '';
        position: absolute;
        inset: -1px;
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.95));
        border-radius: 12px;
        z-index: -1;
        filter: blur(1px);
      }
      
      user-select: text;
      -webkit-user-select: text;
      -moz-user-select: text;
      -ms-user-select: text;

      @media (max-width: 768px) {
        padding: 28px;
      }

      // ==================== 🎯 统一企业级表单样式 ====================
      
      // 表单项间距 - 8px网格系统
      :deep(.el-form-item) {
        margin-bottom: 16px; // 8px * 2
        
        &:last-child {
          margin-bottom: 0;
        }
      }

      // 输入框 - 行业标准设计（参考 Stripe/Linear）
      :deep(.el-input__wrapper) {
        background: #ffffff;
        border: 1.5px solid #e1e4e8; // 加粗边框
        border-radius: 8px; // 更大圆角
        padding: 10px 14px; // 更舒适的内边距
        height: 48px; // 标准高度 (8px * 6)
        transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);

        &.is-focus {
          background: #ffffff;
          border-color: var(--theme-primary);
          border-width: 2px; // 聚焦加粗
          padding: 9px 13px; // 补偿边框
          box-shadow: 
            0 0 0 3px color-mix(in srgb, var(--theme-primary) 12%, transparent),
            0 2px 4px rgba(0, 0, 0, 0.1);
          transform: translateY(-1px); // 微妙上浮
        }

        &:hover:not(.is-focus):not(.is-disabled) {
          border-color: #b1b5ba;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
        }
      }

      // 输入框文字
      :deep(.el-input__inner) {
        font-size: 15px; // 更大字体
        color: #24292f; // 更深颜色，更易读
        line-height: 1.6;
      }

      // 占位符
      :deep(.el-input__inner::placeholder) {
        color: #8c959f; // 更清晰的灰色
        font-weight: 400;
      }

      // 图标
      :deep(.el-input__prefix),
      :deep(.el-input__suffix) {
        color: #57606a; // 更深的图标颜色
        
        .el-icon {
          font-size: 18px; // 稍大的图标
        }
      }

      // 主按钮 - 行业标准（参考 GitHub Primer）
      :deep(.el-button--primary) {
        height: 48px; // 8px * 6
        padding: 12px 24px;
        font-size: 15px;
        font-weight: 600; // 更粗的字重
        border-radius: 8px; // 与输入框一致
        border: none;
        background: var(--theme-primary);
        box-shadow: 
          0 1px 0 rgba(27, 31, 36, 0.04),
          inset 0 1px 0 rgba(255, 255, 255, 0.25); // 内光
        transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
        letter-spacing: 0.02em; // 字间距

        &:hover:not(.is-disabled):not(.is-loading) {
          background: color-mix(in srgb, var(--theme-primary) 92%, black);
          box-shadow: 
            0 3px 8px rgba(0, 0, 0, 0.12),
            0 1px 3px rgba(0, 0, 0, 0.08),
            inset 0 1px 0 rgba(255, 255, 255, 0.25);
          transform: translateY(-1px);
        }

        &:active:not(.is-disabled):not(.is-loading) {
          transform: translateY(0);
          box-shadow: 
            inset 0 1px 0 rgba(27, 31, 36, 0.15),
            inset 0 1px 0 rgba(255, 255, 255, 0.25);
        }
      }

      // 默认按钮
      :deep(.el-button--default) {
        height: 48px;
        padding: 12px 24px;
        font-size: 14px;
        font-weight: 500;
        border-radius: 8px;
        border: 1px solid #d1d5db;
        background: #ffffff;
        color: #24292f;
        box-shadow: 
          0 1px 0 rgba(27, 31, 36, 0.04),
          inset 0 1px 0 rgba(255, 255, 255, 0.25);
        transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);

        &:hover:not(.is-disabled) {
          background: #f6f8fa;
          border-color: #b1b5ba;
          box-shadow: 
            0 2px 4px rgba(0, 0, 0, 0.08),
            inset 0 1px 0 rgba(255, 255, 255, 0.25);
        }
        
        &:active:not(.is-disabled) {
          background: #ebf0f4;
          box-shadow: inset 0 1px 0 rgba(27, 31, 36, 0.15);
        }
      }

      // 复选框 - 更大更清晰
      :deep(.el-checkbox) {
        .el-checkbox__inner {
          width: 18px; // 更大
          height: 18px;
          border-radius: 4px;
          border: 1.5px solid #d1d5db;
          transition: all 0.15s ease;
          
          &:hover {
            border-color: var(--theme-primary);
          }
        }

        &.is-checked .el-checkbox__inner {
          background-color: var(--theme-primary);
          border-color: var(--theme-primary);
          
          &::after {
            border-width: 2px; // 更粗的勾
          }
        }
        
        .el-checkbox__label {
          font-size: 14px;
          color: #24292f;
          padding-left: 8px;
        }
      }

      // 链接
      :deep(.el-link) {
        color: var(--theme-primary);
        font-size: 14px;
        font-weight: 500;
        
        &:hover {
          color: color-mix(in srgb, var(--theme-primary) 80%, black);
        }
      }

      // 标签页切换 - 行业标准（参考 GitHub Underline Tabs）
      .tab-switcher {
        margin-bottom: 24px; // 8px * 3
        border-bottom: 1px solid #d1d5db;
        
        .tab-buttons {
          display: flex;
          gap: 8px; // 8px网格
          
          .tab-btn {
            padding: 12px 16px; // 8px网格
            border: none;
            background: transparent;
            color: #57606a;
            font-size: 14px;
            font-weight: 500;
            border-bottom: 2px solid transparent;
            cursor: pointer;
            transition: all 0.15s ease;
            display: flex;
            align-items: center;
            gap: 6px;
            position: relative;
            bottom: -1px;
            
            .tab-icon {
              font-size: 16px;
              transition: transform 0.15s ease;
            }
            
            &.active {
              color: #24292f;
              border-bottom-color: var(--theme-primary);
              font-weight: 600;
              
              .tab-icon {
              color: var(--theme-primary);
              }
            }
            
            &:hover:not(.active) {
              color: #24292f;
              border-bottom-color: #d1d5db;
              
              .tab-icon {
                transform: translateY(-1px);
              }
            }
          }
        }
      }

      // 返回按钮
      .back-header {
        margin-bottom: 24px;

        :deep(.el-button) {
          color: rgba(0, 0, 0, 0.65);
          font-size: var(--font-size-sm);

          &:hover {
            color: var(--theme-primary);
          }
        }
      }

      // 表单内容
      .form-content {
        position: relative;
      }
    }

    .bottom-info {
      margin-top: 24px;
      text-align: center;

      .help-links {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        flex-wrap: wrap;

        .link-item {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          font-size: 13px;
          color: rgba(255, 255, 255, 0.9);
          text-decoration: none;
          transition: all 0.3s;

          .link-icon {
            font-size: 14px;
          }

          &:hover {
            color: white;
            transform: translateY(-1px);
          }
        }

        .separator {
          color: rgba(255, 255, 255, 0.5);
          font-size: 12px;
        }
      }
    }
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(60px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}


// ==================== 页脚 ====================
.page-footer {
  padding: 20px;
  text-align: center;
  position: relative;
  z-index: 15;
  margin-top: auto;
  background: rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);

  p {
    margin: 0;
    font-size: var(--font-size-xs);
    font-weight: 400;
    color: rgba(255, 255, 255, 0.9);
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  }

  @media (max-width: 768px) {
    padding: 16px;
  }
}

// ==================== 过渡动画 ====================
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-slide-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

// ==================== 响应式优化 ====================
@media (max-width: 1200px) {
  .main-content {
    gap: 48px;
  }
}

@media (max-width: 768px) {
  .login-container {
    // 移动端简化背景
    .animated-background {
      .gradient-orb {
        opacity: 0.2;
        filter: blur(120px);
      }

      .wave-container {
        height: 80px;
      }
    }
  }

  .theme-switcher {
    top: 12px;
    right: 12px;

    .theme-btn {
      width: 40px;
      height: 40px;

      .theme-icon {
        font-size: 18px;
      }
    }
  }

  .main-content {
    flex-direction: column;
    padding: 24px 16px 16px;
    gap: 24px;
  }

  .brand-section,
  .form-section {
    max-width: 100%;
    width: 100%;
  }

  .brand-section {
    // 移动端品牌区改为紧凑横幅
    .brand-wrapper {
      .logo-area {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        text-align: left;

        .logo-icon {
          width: 48px;
          height: 48px;
          margin: 0;
          animation: none;
        }

        .brand-title {
          font-size: 22px;
          margin: 0;
          line-height: 1.2;
        }

        .brand-tagline,
        .brand-slogan {
          display: none; // 移动端隐藏副标题
        }
      }
    }
  }

  .form-section {
    .form-wrapper .glass-card {
      padding: 24px 20px;
      
      .tab-switcher {
        margin-bottom: 20px;

        .tab-buttons .tab-btn {
          padding: 6px 16px;
          font-size: var(--font-size-xs);
        }
      }

      :deep(.el-input__wrapper) {
        height: 40px;
      }

      :deep(.el-button--primary),
      :deep(.el-button--default) {
        height: 40px;
        padding: 6px 20px;
        font-size: var(--font-size-sm);
      }
    }
  }
}
</style>

